//////////////////////////////////////////////////////////////////////////////////////////////////
//
// LONG HISTORY....
//
//
// The problem:
//
// The installer executes the Custom Action as NT AUTHORITY\SYSTEM user.
// So once it ends, the "commit" custom action opens the Browser to install the Factory Client.
// The clickonce application get installed for the NT AUTHORITY\SYSTEM, instead o the current user.
//
// The solution:
//
// We can manually change the MSI file to execute the custom action as the current user.
// We do that setting the Type flag of the CustomAction table.
// It can be done manually using ORCA, or as a Post-Build event, as we did here.
//
//
// READ: http://mehranikoo.net/CS/archive/2008/12/23/WindowsInstallerCustomActionsWindowsVistaAndTerminalServer.aspx
//
//
//////////////////////////////////////////////////////////////////////////////////////////////////

// Constant values from Windows Installer
var msiOpenDatabaseModeTransact = 1;

var msiViewModifyInsert         = 1
var msiViewModifyUpdate         = 2
var msiViewModifyAssign         = 3
var msiViewModifyReplace        = 4
var msiViewModifyDelete         = 6

var msidbCustomActionTypeInScript       = 0x00000400;
var msidbCustomActionTypeNoImpersonate  = 0x00000800;

if (WScript.Arguments.Length != 1)
{
	WScript.StdErr.WriteLine(WScript.ScriptName + " file");
	WScript.Quit(1);
}

var filespec = WScript.Arguments(0);
var installer = WScript.CreateObject("WindowsInstaller.Installer");
var database = installer.OpenDatabase(filespec, msiOpenDatabaseModeTransact);

var sql
var view
var record

try
{
	sql = "SELECT `Action`, `Type`, `Source`, `Target` FROM `CustomAction`";
	view = database.OpenView(sql);
	view.Execute();
	record = view.Fetch();
	while (record)
	{	    
	    if (record.StringData(1)=="_3BEF66A0_93C4_4CC4_A5D4_A4DAD232AE9C.commit")
	    {
		WScript.StdOut.Write("NoImpersonate CHANGED for custom action Commit.");
	        record.IntegerData(2) = 1537;
        	view.Modify(msiViewModifyReplace, record);
	    }
        record = view.Fetch();
	}

	view.Close();
	database.Commit();
}
catch(e)
{
	WScript.StdErr.WriteLine(e);
	WScript.Quit(1);
}
WScript.StdOut.Write("NoImpersonate Script ended.");